package com.longway.common.controller;

import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;
import com.longway.common.kit.JStrKit;
import com.longway.core.toolbox.support.SqlKeyword;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ZtreeController extends BaseController {
	
//	@RequestMapping("/open/{type0}/{index1}/{name2}/{source3}/{check4}/{where5}/{intercept6}/{ext7}/{val8}/{search9}/{async10}/{async11}/Y12/N13")
	public void open(){
		setAttr("type", getTypeName(getPara(0), getPara(3)));
		setAttr("index", getPara(1));
		setAttr("name", getPara(2));
		setAttr("source", getPara(3));
		setAttr("check", getPara(4));
		setAttr("where", getPara(5));
		setAttr("intercept", getPara(6));
		setAttr("ext", getPara(7));
		setAttr("val", getPara(8));
		setAttr("search", getPara(9));
		setAttr("async", getPara(10));
		setAttr("initParam", getPara(11));
		setAttr("Y", getPara(12));
		setAttr("N", getPara(13));
		render("/view/common/_function/_ztree.html");
	}
	
	public void getTreeListAsync() {	
		String type = getPara("type");
		String source = getPara("source");
		String val = getPara("val","");
		String key = getPara("key","id");
		String parameter = getPara("parameter");
		Map<String, String> mapparam = SqlKeyword.getSqlMapDeCode2(parameter);	
		SqlPara sqlSource = getSqlAsync(type, source ,mapparam);
		List<Record> list = Db.find(sqlSource); 
		
		if(type.indexOf("dict") >= 0){
			key = "num";
		}
		String [] arr = val.split(",");
		for(Record record : list){
			for(String v : arr){
				if(JStrKit.format(record.get(key)).equals(v) && !v.equals("0")){
					record.set("checked", "true");
				}
			}
		}
		
		renderJson(list);
	}
	
	public void getTreeListNameAsync(){
		String type = getPara("type");
		String source = getPara("source");
		if(StrKit.notBlank(source)){
			source = source.replace("0x2E", ".");
		}
		String val = getPara("val");
		String key = getPara("key","id");
		Map<String, String> mapparam = new HashMap<String, String>();
		int i = 0;
		for(String id : val.split(",")){
			if(i==0){
				mapparam.put(key+"=", id);
			}else{
				mapparam.put(" or "+key +"=", id);
			}
			i++;
		}
		type = getTypeName(type, source);
		SqlPara sqlSource = getSqlAsync(type, source ,mapparam);
		List<Record> list = CacheKit.get(DICT_CACHE, "ztree_list_" + val,
				new IDataLoader() {
					@Override
                    public List<Record> load() {
						return Db.find(sqlSource);
					}
				});
		String name = "";
		if(type.indexOf("dict") >= 0){
			key = "num";
		}
		String [] arr = val.split(",");
		for(Record record : list){
			for(String v : arr){
				if(JStrKit.format(record.get(key)).equals(v)){
					name += record.get("name") + ",";
				}
			}
		}
		name = JStrKit.removeSuffix(name, ",");
		Ret ret = Ret.create("name", name).set("nodes", list);
		renderJson(ajaxSucess(ret));
	}
	
	public void getTreeList() {	
		String type = getPara("type");
		String source = getPara("source");
		String val = getPara("val","");
		String key = getPara("key","id");
		String parameter = getPara("parameter");
		Map<String, String> mapparam = SqlKeyword.getSqlMapDeCode2(parameter);	
		SqlPara sqlSource = getSql(type, source ,mapparam);
		List<Record> list = Db.find(sqlSource); 
		if(type.indexOf("dict") >= 0){
			key = "num";
		}
		String [] arr = val.split(",");
		for(Record record : list){
			for(String v : arr){
				if(JStrKit.format(record.get(key)).equals(v) && !v.equals("0")){
					record.set("checked", "true");
				}
			}
		}
		
		renderJson(ajaxSucess(list));
	}
	
	public void getTreeListName(){
		String type = getPara("type");
		String source = getPara("source");
		String val = getPara("val");
		String key = getPara("key","id");
		Map<String, String> mapparam = new HashMap<String, String>();
		int i = 0;
		for(String id : val.split(",")){
			if(i==0){
				mapparam.put(key+"=", id);
			}else{
				mapparam.put(" or "+key +"=", id);
			}
			i++;
		}
		type = getTypeName(type, source);
		SqlPara sqlSource = getSql(type, source,mapparam);
		List<Record> list = CacheKit.get(DICT_CACHE, "ztree_list_" + val,
				new IDataLoader() {
					@Override
                    public List<Record> load() {
						return Db.find(sqlSource);
					}
				});
		
		String name = "";
		if(type.indexOf("dict") >= 0){
			key = "num";
		}
		String [] arr = val.split(",");
		for(Record record : list){
			for(String v : arr){
				if(JStrKit.format(record.get(key)).equals(v)){
					name += record.get("name") + ",";
				}
			}
		}
		name = JStrKit.removeSuffix(name, ",");
		Ret ret = Ret.create("name", name).set("nodes", list);
		renderJson(ajaxSucess(ret));
	}
	
	private String getTypeName(String type, String source){
		if(type.indexOf("opentreeUser") >= 0 || type.indexOf("selecttreeUser") >= 0){
			type = "user";
		} else if(type.indexOf("opentreeDept") >= 0 || type.indexOf("selecttreeDept") >= 0){
			type = "dept";
		} else if(type.indexOf("opentreeRole") >= 0 || type.indexOf("selecttreeRole") >= 0){
			type = "role";
		} else if(type.indexOf("opentree_") >= 0 || type.indexOf("opentreeDict") >= 0 ||type.indexOf("selecttree_") >= 0 || type.indexOf("selecttreeDict") >= 0||type.indexOf("dict_") >= 0){
			type = "dict_" + type.replace("opentree_", "").replace("opentreeDict", "").replace("selecttree_", "").replace("selecttreeDict", "").replace("dict_", "");
		} else {
			type = "diy_" + source.replace("dict", "dct");
		}
		return type;
	}
	
	private SqlPara getSql(String type, String source ,Map<String,String> param){
		SqlPara sqlPara = null;
		if(StrKit.notBlank(source)){
			source = source.replace("0x2E", ".");
		}
		String sql = "";
		if(type.indexOf("dict") >= 0) {
			String code = type.replace("dict_", "");
			sql = "select num as \"num\",id as \"id\",pid as \"pId\",name as \"name\",(case when (pid=0 or pid is null) then 'true' else 'false' end) \"open\"  from  base_dict where code = #para(0)";
			sqlPara = Db.getSqlParaByString(sql, code);
		} else if (type.equals("user")) {
			sqlPara = Db.getSqlPara("user.opentreeDeptDiy" ,param);
		} else if (type.equals("dept")) {
			sql = "select id as \"id\",pid as \"pId\",simpleName as \"name\",(case when (pid=0 or pid is null) then 'true' else 'false' end) \"open\" from  base_dept where 1=1 #if(deptId) and id = #para(deptId) #end";
			sqlPara = Db.getSqlParaByString(sql, param);
		} else if (type.equals("role")) {
			sql = "select id as \"id\",pid,name as \"name\",(case when (pid=0 or pid is null) then 'true' else 'false' end) \"open\" from  base_role where 1=1 #if(roleId) and id= #para(roleId) #end #if(deptId) and deptid= #para(deptId) #end";
			sqlPara = Db.getSqlParaByString(sql, param);
		} else {
			sqlPara = Db.getSqlPara(source ,param);
		}
		return sqlPara;
	}
	
	
	private SqlPara getSqlAsync(String type, String source ,Map<String,String> param){
		SqlPara sqlPara = null;
		if(StrKit.notBlank(source)){
			source = source.replace("0x2E", ".");
		}
		if(type.indexOf("diy") >= 0)
		{
			sqlPara = Db.getSqlPara(source ,param);
		}
		return sqlPara;
	}
	
	/*public static void main(String[] args) {
		String test="pid=selected%20and%20countyid=452";
		test = test.replaceAll("selected", "ryc");
		System.out.println(test);
	}*/
}
